package main.java.com.epam;

import java.io.File;
import java.lang.reflect.Method;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

public class ClassLoaderApp {

        public static void main(String[] args) throws Exception {

                //create compilation unit file
                File javaFile = new File("TestModule.java");
               
                //create edit compilation unit
                Process javaFileEditProcess = Runtime.getRuntime().exec("notepad " + javaFile.getAbsolutePath());

                //waiting for editing complete
                if (javaFileEditProcess.waitFor() != 0) {
                        throw new Exception("Editing terminated");
                }

//                //compiling java file
//                Process compilationProcess = Runtime.getRuntime().exec("javac  " + file.getAbsolutePath());
//               
//                //waiting for compilation complete
//                if (compilationProcess.waitFor() != 0) {
//                        throw new CompilationException(compilationProcess, "compilation mistakes");
//                }

                JavaCompiler jc = ToolProvider.getSystemJavaCompiler();  
                StandardJavaFileManager sjfm = jc.getStandardFileManager(null, null, null); 
                Iterable<? extends JavaFileObject> fileObjects = sjfm.getJavaFileObjects(javaFile);  
                System.out.println(jc.getTask(null, sjfm, null, null, null, fileObjects).call());  
                try{
                    sjfm.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
                
                //loading class
                MyClassLoader myClassLoader = new MyClassLoader();
                myClassLoader.setup(javaFile.getAbsolutePath().substring(0, javaFile.getAbsolutePath().lastIndexOf(".")));
                Class<?> c = myClassLoader.findClass();
               
                //new instance of a class
                Object object = c.newInstance();
               
                //
                System.out.println(object);
               
                //getting method
                Method method = object.getClass().getMethod("m1", new Class[]{String.class,     int.class});  
               
                //method invokation
                method.invoke(object, new Object[]{"bla-bla", 5} );
       
//              TestModule testModule = new TestModule();
//              
//              System.out.println(testModule.equals(object));
               
        }//main
}//App1
